package com.genius.dingding.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.genius.workflow.util.DBUtils;

public class PowerUtil {
	
	private static final Logger LOGGER = Logger.getLogger(PowerUtil.class);

	/**
	 * 获取管店信息表
	 * @param dataBaseName
	 * @param tableName
	 * @return 存在为true
	 */
	public static String getTuserstorehistory(Connection conn,String date,String caiji) {
		String tableName = null;
		try {
			//判定是否是带日期查询
			if(date != null){
				String sql = "SELECT left(dTradeDate,7)dTradeDate,left(CURDATE(),7)nowDate FROM "+caiji+".dict_tuserstorehistory"
						+ " where dTradeDate = DATE_FORMAT('"+date+"','%Y-%m-01 00:00:00')";
				ResultSet rs = DBUtils.query(conn, sql);
				//查询到，有数据，
				if(rs.next()){
					//判断是不是当月，是当月取指标库，不是取采集库
					if("".equals(caiji)){
						tableName = "dict_tuserstorehistory where dTradeDate = DATE_FORMAT('"+date+"','%Y-%m-01 00:00:00')";
					}else{
						if(date.substring(0, 7).equals(rs.getString("nowDate"))){
							tableName = "dict_tuserstorehistory where 1=1";
						}else{
							tableName = caiji+".dict_tuserstorehistory where dTradeDate = DATE_FORMAT('"+date+"','%Y-%m-01 00:00:00')";
						}
					}
				}else{
					//判断采集库和指标库是否是同一库，如果是同一库，取最大日期
					if("".equals(caiji)){
						tableName = "dict_tuserstorehistory where dTradeDate = (SELECT max(dTradeDate) from dict_tuserstorehistory)";
					}else{
						tableName = "dict_tuserstorehistory where 1=1";
					}
				}
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			LOGGER.error(e);
		} 
		return tableName;
	}
	/**
	 * 获取管店信息表,获取日期相差的
	 * @param dataBaseName
	 * @param tableName
	 * @return 存在为true
	 */
	public static String getTuserstorehistory(Connection conn,String date,int dateCha,String chaType,String caiji) {
		String tableName = null;
		try {
			//判定是否是带日期查询
			if(date != null){
				String sql = "SELECT left(dTradeDate,7)dTradeDate,left(CURDATE(),7)nowDate FROM "+caiji+".dict_tuserstorehistory"
						+ " where dTradeDate = DATE_FORMAT(DATE_ADD('"+date+"',INTERVAL "+dateCha+" "+chaType+"),'%Y-%m-01 00:00:00')";
				ResultSet rs = DBUtils.query(conn, sql);
				//查询到，有数据，
				if(rs.next()){
					//判断是不是当月，是当月取指标库，不是取采集库
					if(date.substring(0, 7).equals(rs.getString("nowDate"))){
						tableName = "dict_tuserstorehistory where 1=1";
					}else{
						tableName = caiji+".dict_tuserstorehistory where dTradeDate = DATE_FORMAT('"+date+"','%Y-%m-01 00:00:00')";
					}
				}else{
					//判断采集库和指标库是否是同一库，如果是同一库，取最大日期
					if("".equals(caiji)){
						tableName = "dict_tuserstorehistory where dTradeDate = (SELECT max(dTradeDate) from dict_tuserstorehistory)";
					}else{
						tableName = "dict_tuserstorehistory where 1=1";
					}
				}
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			LOGGER.error(e);
		} 
		return tableName;
	}
}